const dbmodel = require('../dbmodel/dbmodel.js');
const post = dbmodel.model('posts');
const like = dbmodel.model('like');

// 更改文章的点赞数量
let postInfoChange = function(postID, value, success, fail, res) {
	let wherestr = {
		'_id': postID
	}
	let query = post.find(wherestr);

	// 查询结果
	query.exec().then(function(e) {
		post.updateOne(wherestr, {
			like: value
		}, function(err, result) {
			if (err) {
				res.send({
					status: 500,
					info: fail
				});
			} else {
				res.send({
					status: 200,
					info: success
				})
			}
		})
	}).catch(function(err) {
		res.send({
			status: 500,
			err
		})
	})
}
// 点赞文章
exports.postLike = function(req, res) {
	let success = '点赞成功'
	let fail = '点赞失败！！！'
	let data = {
		postID: req.body.postID,
		userID: req.body.userID,
		createTime: new Date()
	}

	let Like = new like(data);

	Like.save(function(err, result) {
		if (err) {
			res.send({
				status: 500,
				info: fail
			});
		} else {
			postInfoChange(req.body.postID, req.body.value, success, fail, res)
		}
	})
}
// 取消点赞文章
exports.delPostLike = function(req, res) {
	let success = '取消点赞成功'
	let fail = '取消点赞失败！！！'
	let data = {
		postID: req.body.postID,
		userID: req.body.userID
	}

	like.deleteOne(data, function(err, result) {
		if (err) {
			res.send({
				status: 500,
				info: fail
			});
		} else {
			postInfoChange(req.body.postID, req.body.value, success, fail, res)
		}
	})
}
// 判断是否点赞文章
exports.isPostLike = function(req, res) {
	let wherestr = {
		'postID': req.body.postID,
		'userID': req.body.userID
	}
	let out = {
		'postID': 1,
		'userID': 1
	}
	like.findOne(wherestr, out, function(err, result) {
		if (err) {
			res.send({
				status: 500
			});
		} else {
			res.send({
				status: 200,
				result
			});
		}
	})
}
